/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package za.co.pas.jtorrenttracker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 *
 * @author alabuschagne
 */
public class Comms
{
    public Comms()
    {
    }

    public void connect(String strURL, byte[] infohash) throws MalformedURLException, IOException
    {
        strURL = strURL.toLowerCase();
        StringBuilder sb = new StringBuilder(strURL);
        sb.append("?");
        sb.append("info_hash=");
        sb.append(new String(infohash));
        if(strURL.startsWith("http"))
        {
            //URLEncoder
            
            URL httpURL = new URL(sb.toString());
            //System.out.println(httpURL.getPort());
            URLConnection httpCon = httpURL.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String inputLine;

            while((inputLine = in.readLine()) != null)
            {
                System.out.println(inputLine);
            }
            in.close();
        }
        else if(strURL.startsWith("udp"))
        {
            DatagramSocket socket = new DatagramSocket();

            // send request
            byte[] buf = new byte[256];
            InetAddress address = InetAddress.getByName(strURL);
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
            socket.send(packet);

            // get response
            packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);

            // display response
            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println(received);

            socket.close();
        }

    }
}
